package com.ruoyi.common.utils;


import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import kong.unirest.HttpResponse;
import kong.unirest.JsonNode;
import kong.unirest.Unirest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

import static com.ruoyi.common.utils.Threads.sleep;
import static com.ruoyi.common.utils.TiffUtil.writeImage;

/**
 * 生成图片
 */
public class RunninGubUtils {

    private static final Logger log = LoggerFactory.getLogger(RunninGubUtils.class);

    private static final int maxRetries = 20; // 最大重试次数
    private static final long waitTimeMs = 10000; // 每次等待 10 秒

    static {
        Unirest.config()
                .connectTimeout(300000)
                .socketTimeout(300000)
                .concurrency(200, 20); // 设置连接池参数
    }


    private static void addNodeInfo(JSONArray nodeInfoList, String nodeId, String fieldName, String fieldValue) {
        JSONObject nodeInfo = new JSONObject();
        nodeInfo.put("nodeId", nodeId);
        nodeInfo.put("fieldName", fieldName);
        nodeInfo.put("fieldValue", fieldValue);
        nodeInfoList.add(nodeInfo);
    }


    //{"code":0,"msg":"success","data":{"netWssUrl":"wss://www.runninghub.cn:443/ws/c_instance?c_host=10.129.240.27&c_port=80&clientId=7a7069b9db2817773edadabbb7a9a7cb&workflowId=1916774404947382274&Rh-Comfy-Auth=eyJ1c2VySWQiOiIwMWFjYjRlOWQ2NzA3MmMwZjk5NzNiZTdhZDIzYjc0ZiIsInNpZ25FeHBpcmUiOjE3NDY2ODAxOTM2ODUsInRzIjoxNzQ2MDc1MzkzNjg1LCJzaWduIjoiYjU2MzFkNmE3YWNjNmVjZGMwODA3NTIyMWIyZTI5ODEifQ%3D%3D&target=https://hbxy.runninghub.cn:11143","taskId":"1917805318477365250","clientId":"7a7069b9db2817773edadabbb7a9a7cb","taskStatus":"RUNNING","promptTips":"{\"result\": true, \"error\": null, \"outputs_to_execute\": [\"48\", \"65\", \"64\", \"49\"], \"node_errors\": {}}"}}
    public static String outputs(String taskId) {
        // 单独输入参数
        String apiKey = "2c7c46dd6c04426d9904de16ccf95353";

        // 构建请求体
        JSONObject requestBody = new JSONObject();
        requestBody.put("apiKey", apiKey);
        requestBody.put("taskId", taskId);


        int retryCount = 0;
        String fileUrl = "";
        while (retryCount < maxRetries) {
            HttpResponse<String> response = Unirest.post("https://www.runninghub.cn/task/openapi/outputs")
                    .header("Host", "www.runninghub.cn")
                    .header("Content-Type", "application/json")
                    .body(requestBody.toString())
                    .asString();


            if (response.getStatus() == 200) {
                String jsonBody = response.getBody().toString();
                try {
                    JSONObject json = JSONObject.parseObject(jsonBody);
                    if (json.getIntValue("code") == 0) {
                        JSONArray data = json.getJSONArray("data");
                        if (data != null && !data.isEmpty()) {
                            JSONObject firstItem = data.getJSONObject(0);
                            fileUrl = firstItem.getString("fileUrl");
                            System.out.println("文件URL: " + fileUrl);
                        }
                        break; // 成功获取 文件URL，退出循环
                    } else if (json.getIntValue("code") == 804) {
                        System.out.println("任务正在运行，等待后重试（第 " + (retryCount + 1) + " 次）");
                        log.info("任务正在运行，等待后重试（第 " + (retryCount + 1) + " 次）");
                        retryCount++;
                        try {
                            Thread.sleep(waitTimeMs);
                        } catch (InterruptedException e) {
                            Thread.currentThread().interrupt();
                        }
                    } else {
                        log.info("其他错误：" + json);
                        System.out.println("任务正在运行，等待后重试（第 " + (retryCount + 1) + " 次）");
                        log.info("任务正在运行，等待后重试（第 " + (retryCount + 1) + " 次）");
                        retryCount++;
                        try {
                            Thread.sleep(waitTimeMs);
                        } catch (InterruptedException e) {
                            Thread.currentThread().interrupt();
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }


        return fileUrl;

    }

    public static String run(String fileName,String buildType) {

        // 定义基本参数
//        String webappId = "1916783251497615362";
//        String webappId = "1921149755529838593";
        String lora_name = "";
        String webappId = "";
        String seed = "";

        if (buildType.equals("0")){
            webappId = "1924357509190963202";
            seed = "240298702711908";
        }else if (buildType.equals("1")){
            webappId = "1924357287920455682";
            seed = "364811433685308";
        }else if (buildType.equals("2")){
            webappId = "1924356781454053378";
            seed = "214028605575537";
        }


//        String webappId = "1921149755529838593";
//        String webappId = "1920798761663270914";
        String apiKey = "2c7c46dd6c04426d9904de16ccf95353";
//        String apiKey = "64d55dfddc65402c9e67862720a4bb13";
//        String apiKey = "64d55dfddc65402c9e67862720a4bb13";

        // 定义 nodeInfoList 数组
        JSONArray nodeInfoList = new JSONArray();
//
//        // 添加节点信息
//        addNodeInfo(nodeInfoList, "58:0", "ckpt_name", "AWPainting_v1.5.safetensors");
//        addNodeInfo(nodeInfoList, "58:1", "condition", "always");
//        addNodeInfo(nodeInfoList, "58:1", "height", "700");
//        addNodeInfo(nodeInfoList, "58:1", "interpolation", "nearest");
//        addNodeInfo(nodeInfoList, "58:1", "method", "keep proportion");
//        addNodeInfo(nodeInfoList, "58:1", "multiple_of", "0");
//        addNodeInfo(nodeInfoList, "58:1", "width", "560");
//        addNodeInfo(nodeInfoList, "58:2", "lora_name", "中国风-水墨佳人-二次元_动漫_yygf v1.0.safetensors");
//        addNodeInfo(nodeInfoList, "58:2", "strength_model", "0.6");
//        addNodeInfo(nodeInfoList, "48", "character_threshold", "0.85");
//        addNodeInfo(nodeInfoList, "48", "model", "wd-v1-4-moat-tagger-v2");
//        addNodeInfo(nodeInfoList, "48", "threshold", "0.35");
//        addNodeInfo(nodeInfoList, "58:3", "text", "(worst quality:1.5),(low quality:1.5),(normal quality:1.5),lowres,watermark,,nsfw\n");
//        addNodeInfo(nodeInfoList, "16", "image", fileName);
//        addNodeInfo(nodeInfoList, "58:5", "denoise", "1");
//        addNodeInfo(nodeInfoList, "58:5", "seed", "101508456039626");
        addNodeInfo(nodeInfoList, "68", "vae_name", "ae.safetensors");
        addNodeInfo(nodeInfoList, "49", "denoise", "1");
        addNodeInfo(nodeInfoList, "49", "seed", seed);
        addNodeInfo(nodeInfoList, "39", "image", fileName);
        addNodeInfo(nodeInfoList, "102", "text", "cartoon2.5D style");
        addNodeInfo(nodeInfoList, "43", "text_input", "");




        // 构建请求体
        JSONObject requestBody = new JSONObject();
        requestBody.put("webappId", webappId);
        requestBody.put("apiKey", apiKey);
        requestBody.put("nodeInfoList", nodeInfoList);


        String taskId = "";
        int retryCount = 0;

        while (retryCount < maxRetries) {
            HttpResponse<JsonNode> response = Unirest.post("https://www.runninghub.cn/task/openapi/ai-app/run")
                    .header("Host", "www.runninghub.cn")
                    .header("Content-Type", "application/json")
                    .body(requestBody.toString())
                    .asJson();


            if (response.getStatus() == 200) {
                String jsonBody = response.getBody().toString();
                try {
                    JSONObject json = JSONObject.parseObject(jsonBody);
                    if (json.getIntValue("code") == 0) {
                        JSONArray data = json.getJSONArray("data");
                        if (data != null && !data.isEmpty()) {
                            JSONObject firstItem = data.getJSONObject(0);
                            taskId = firstItem.getString("taskId");
                            System.out.println("taskId: " + taskId);
                            log.info("taskId: " + taskId);

                        }

                        break; // 成功获取 taskId，退出循环
                    } else if (json.getIntValue("code") == 804) {
                        System.out.println("任务正在运行，等待后重试（第 " + (retryCount + 1) + " 次）");
                        log.info("任务正在运行，等待后重试（第 " + (retryCount + 1) + " 次）");
                        retryCount++;
                        try {
                            Thread.sleep(waitTimeMs);
                        } catch (InterruptedException e) {
                            Thread.currentThread().interrupt();
                        }
                        System.out.println(jsonBody);
                        log.info(jsonBody);
                    } else {
                        System.out.println("其他错误：" + json.getString("msg"));
                        log.info("其他错误：" + json.getString("msg"));
                        System.out.println("任务正在运行，等待后重试（第 " + (retryCount + 1) + " 次）");
                        log.info("任务正在运行，等待后重试（第 " + (retryCount + 1) + " 次）");
                        retryCount++;
                        try {
                            Thread.sleep(waitTimeMs);
                        } catch (InterruptedException e) {
                            Thread.currentThread().interrupt();
                        }
                        System.out.println(jsonBody);
                        log.info(jsonBody);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        return taskId;
    }

    public static String runT(String fileName) {

        String webappId = "1921149755529838593";
//        String webappId = "1920798761663270914";
        String apiKey = "2c7c46dd6c04426d9904de16ccf95353";
//        String apiKey = "64d55dfddc65402c9e67862720a4bb13";
//        String apiKey = "64d55dfddc65402c9e67862720a4bb13";

        // 定义 nodeInfoList 数组
        JSONArray nodeInfoList = new JSONArray();
//
//        // 添加节点信息
        addNodeInfo(nodeInfoList, "58:0", "ckpt_name", "AWPainting_v1.5.safetensors");
        addNodeInfo(nodeInfoList, "58:1", "condition", "always");
        addNodeInfo(nodeInfoList, "58:1", "height", "700");
        addNodeInfo(nodeInfoList, "58:1", "interpolation", "nearest");
        addNodeInfo(nodeInfoList, "58:1", "method", "keep proportion");
        addNodeInfo(nodeInfoList, "58:1", "multiple_of", "0");
        addNodeInfo(nodeInfoList, "58:1", "width", "560");
        addNodeInfo(nodeInfoList, "58:2", "lora_name", "中国风-水墨佳人-二次元_动漫_yygf v1.0.safetensors");
        addNodeInfo(nodeInfoList, "58:2", "strength_model", "0.6");
        addNodeInfo(nodeInfoList, "48", "character_threshold", "0.85");
        addNodeInfo(nodeInfoList, "48", "model", "wd-v1-4-moat-tagger-v2");
        addNodeInfo(nodeInfoList, "48", "threshold", "0.35");
        addNodeInfo(nodeInfoList, "58:3", "text", "(worst quality:1.5),(low quality:1.5),(normal quality:1.5),lowres,watermark,,nsfw\n");
        addNodeInfo(nodeInfoList, "16", "image", fileName);
        addNodeInfo(nodeInfoList, "58:5", "denoise", "1");
        addNodeInfo(nodeInfoList, "58:5", "seed", "101508456039626");

        // 构建请求体
        JSONObject requestBody = new JSONObject();
        requestBody.put("webappId", webappId);
        requestBody.put("apiKey", apiKey);
        requestBody.put("nodeInfoList", nodeInfoList);


        String taskId = "";
        int retryCount = 0;

        while (retryCount < maxRetries) {
            HttpResponse<JsonNode> response = Unirest.post("https://www.runninghub.cn/task/openapi/ai-app/run")
                    .header("Host", "www.runninghub.cn")
                    .header("Content-Type", "application/json")
                    .body(requestBody.toString())
                    .asJson();


            if (response.getStatus() == 200) {
                String jsonBody = response.getBody().toString();
                try {
                    JSONObject json = JSONObject.parseObject(jsonBody);
                    if (json.getIntValue("code") == 0) {
                        JSONArray data = json.getJSONArray("data");
                        if (data != null && !data.isEmpty()) {
                            JSONObject firstItem = data.getJSONObject(0);
                            taskId = firstItem.getString("taskId");
                            System.out.println("taskId: " + taskId);
                            log.info("taskId: " + taskId);

                        }

                        break; // 成功获取 taskId，退出循环
                    } else if (json.getIntValue("code") == 804) {
                        System.out.println("任务正在运行，等待后重试（第 " + (retryCount + 1) + " 次）");
                        log.info("任务正在运行，等待后重试（第 " + (retryCount + 1) + " 次）");
                        retryCount++;
                        try {
                            Thread.sleep(waitTimeMs);
                        } catch (InterruptedException e) {
                            Thread.currentThread().interrupt();
                        }
                        System.out.println(jsonBody);
                        log.info(jsonBody);
                    } else {
                        System.out.println("其他错误：" + json.getString("msg"));
                        log.info("其他错误：" + json.getString("msg"));
                        System.out.println("任务正在运行，等待后重试（第 " + (retryCount + 1) + " 次）");
                        log.info("任务正在运行，等待后重试（第 " + (retryCount + 1) + " 次）");
                        retryCount++;
                        try {
                            Thread.sleep(waitTimeMs);
                        } catch (InterruptedException e) {
                            Thread.currentThread().interrupt();
                        }
                        System.out.println(jsonBody);
                        log.info(jsonBody);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        return taskId;
    }

    public static String upload(String filePath) {
        log.info("上传的图片地址为：" + filePath);
        HttpResponse<String> response = Unirest.post("https://www.runninghub.cn/task/openapi/upload")
                .header("Host", "www.runninghub.cn")
                .field("apiKey", "2c7c46dd6c04426d9904de16ccf95353")
                .field("file", new File(filePath))
                .field("fileType", "image")
                .asString();

        String jsonBody = response.getBody();
        System.out.println(jsonBody);
        String fileName = "";
        try {
            JSONObject root = JSONObject.parseObject(jsonBody);
            if (root.getIntValue("code") == 0) {
                JSONArray data = root.getJSONArray("data");
                if (data != null && !data.isEmpty()) {
                    JSONObject firstItem = data.getJSONObject(0);
                    fileName = firstItem.getString("fileName");
                    System.out.println("fileName: " + fileName);
                    log.info("upload  fileName: " + fileName);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("解析 JSON 时出错：" + e.getMessage());
            log.info("解析 JSON 时出错：" + e.getMessage());
        }
        return fileName;
//        {"code":0,"msg":"success","data":[{"fileUrl":"https://rh-images.xiaoyaoyou.com/01acb4e9d67072c0f9973be7ad23b74f/output/ComfyUI_00004_ekvgq_1746075427.png","fileType":"png","taskCostTime":"36","nodeId":"65"}]}

    }


    public static void main(String[] args) throws Exception {
//        String path = "D:/download/b00325db-ca98-432e-a0c9-a6d32844a706_b8dca2ddda454b0fa010f26dc7287ea1.png";
//        String run = run("api/346e9de935546b90debeb136d57a45a85d5f7c919541c37767bdb961dca27fc3.png","2");
//        System.out.println(run);
///
//1924455293600804865  0
//        1924455351691718657  1
//1924455408918802434 2
        String outputs = outputs("1924455408918802434");
        System.out.println("outputs: " + outputs);
//
//        String upload = upload(path);
//        System.out.println("upload: " + upload);
//        URL urlfile = new URL("https://rh-images.xiaoyaoyou.com/01acb4e9d67072c0f9973be7ad23b74f/output/ComfyUI_00023_qmxdl_1746886038.png");
//        InputStream inStream = urlfile.openStream();
//        BufferedImage bimg = ImageIO.read(inStream);
//        File f = writeImage(bimg, "E:\\imageio-test-2.tiff");
    }
}
